<template>
  <div>
    <!-- 正式客户 -->
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="qtype" style="width: 170px; margin-right: 2px;">
          <el-option value="csmRgPhone" label="电话" />
          <el-option value="csmCode" label="客户编号" />
          <el-option value="csmName" label="客户名称" />
          <el-option value="csmRgAddress" label="地址" />
          <el-option value="salesmanName" label="销售人员" />
          <el-option value="remark" label="备注" />
          <el-option value="auditor" label="审核人" />
          <el-option value="sfzh" label="身份证号" />
          <el-option value="cardType1" label="使用证" />
          <el-option value="cardType2" label="充值卡" />
          <el-option value="countryName" label="区" />
          <el-option value="streetName" label="街道" />
        </el-select>
        <el-input v-model.trim="txt" placeholder="请输入" clearable @keyup.enter.native="search" />
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="开户日期" value="createTime" />
          <el-option label="销户日期" value="cancelTime" />
          <el-option label="最后订气时间" value="lastBuyDt" />
        </el-select>
        <el-date-picker
          v-model="date"
          clearable
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="所属机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择组织机构',
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
        />
      </el-form-item>
      <el-form-item label="客户类型:" prop="csmType">
        <el-select v-model="query.csmType" clearable placeholder="请选择">
          <el-option
            v-for="item in csmTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态:" prop="csmStatus">
        <el-select v-model="query.csmStatus" clearable placeholder="请选择">
          <el-option
            v-for="item in csmStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户来源:" prop="newFrom">
        <el-select v-model="query.newFrom" clearable placeholder="请选择">
          <el-option
            v-for="item in newFromMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否自提:" prop="isPickUp">
        <el-select v-model="query.isPickUp" clearable placeholder="请选择">
          <el-option :value="1" label="是" />
          <el-option :value="-1" label="否" />
        </el-select>
      </el-form-item>
      <el-form-item label="结款方式:" prop="settlementType">
        <el-select v-model="query.settlementType" clearable placeholder="请选择">
          <el-option :value="1" label="现结" />
          <el-option :value="2" label="月结" />
        </el-select>
      </el-form-item>
      <el-form-item label="排序:" prop="orderBy">
        <el-select v-model="query.orderBy" clearable placeholder="请选择">
          <el-option :value="1" label="按开户日期" />
          <el-option :value="2" label="按积分余额" />
          <el-option :value="3" label="按历史总积分" />
        </el-select>
      </el-form-item>
      <el-form-item label="客户等级:" prop="unCheckQuality">
        <el-select v-model="query.unCheckQuality" clearable placeholder="请选择">
          <el-option
            v-for="item in csmLevelMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;">
      <div>
        <el-button v-permission="2" type="primary" icon="el-icon-circle-plus-outline" @click="addCsm">新增</el-button>
        <!-- <el-button type="primary" icon="el-icon-s-check" @click="batchAudit">批量审核</el-button>
        <el-button type="primary" icon="el-icon-edit" @click="batchEdit">批量修改</el-button> -->
        <el-button type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
        <el-button type="primary" icon="el-icon-map-location" @click="getMap">客户位置</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @current-change="handleCurrentChange"
      @fetch="fetchData"
    />
    <csm-detail ref="csmDetail" />
    <add-csm ref="addCsm" :tree-data="treeData" />
    <editCsm ref="editCsm" :parent-fetch-data="fetchData" :tree-data="treeData" />
    <customerAudit ref="customerAudit" :parent-fetch-data="fetchData" :tree-data="treeData" />
    <insure ref="insure" />
    <normalReceiptsAdd ref="normalReceiptsAdd" />
    <refillCard ref="refillCard" :card-status-map="accCsmcardCardStatusMap" />
    <occupy ref="occupy" />
    <customerLocation ref="customerLocation" />
    <xiaohu ref="xiaohu" :xiao-hu-fn="xiaoHuFn" />
    <exportDiglog ref="export" :xiao-hu-fn="xiaoHuFn" />

  </div>
</template>

<script>
  import { formatColumnMap, parseTime } from '@/utils'
  import moment from 'dayjs'
  import { csmManageQueryList, customerInfo, customerInvocie, customerCancle, customerLocation } from '@/api'
  import CsmDetail from '../../../components/CsmDetailModal'
  import AddCsm from './AddCsm'
  import EditCsm from './EditCsm'
  import CustomerAudit from './CustomerAudit'
  import Insure from './Insure'
  import NormalReceiptsAdd from '@/views/components/NormalReceiptsAdd'
  import RefillCard from './RefillCard'
  import Occupy from './Occupy'
  import CustomerLocation from './CustomerLocation'
  import { mapGetters } from 'vuex'
  import { minDate } from '@/utils/config'
  import xiaohu from './xiaohu'
  // import exportDiglog from './export'

  export default {
    name: 'real-csm-tab',
    components: {
      CsmDetail, AddCsm, EditCsm, CustomerAudit, Insure, NormalReceiptsAdd, RefillCard, Occupy, CustomerLocation, xiaohu,
      exportDiglog: require('./export.vue').default
    },
    props: {
      csmLerel: {
        type: Number,
        required: true
      },
      treeData: {
        type: Array,
        required: true
      },
      customerTypeMap: {
        type: Array,
        required: true
      },
      newFromMap: {
        type: Array,
        required: true
      },
      csmStatusMap: {
        type: Array,
        required: true
      },
      csmLevelMap: {
        type: Array,
        required: true
      },
      csmNewTypeMap: {
        type: Array,
        required: true
      },
      accCsmcardCardStatusMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        qtype: 'csmRgPhone',
        dateType: 'createTime',
        txt: '',
        date: [],
        ids: [],
        actionColWidth: 80,
        invalidStr: '',
        query: {
          csmType: '',
          csmStatus: '',
          newFrom: '',
          isPickUp: '',
          settlementType: '',
          orderBy: 1,
          unCheckQuality: ''
        },
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'userInfo'
      ]),
      csmTypeMap: function() {
        return this.customerTypeMap.filter(item => item !== -1)
      },
      column: function() {
        const cols = [
          {
            type: 'selection'
          },
          {
            prop: 'csmCode',
            label: '客户编号',
            render: (h, { row }) => <el-link onClick={() => this.openCsmDetail(row)}>{row.csmCode}</el-link>
          },
          {
            prop: 'csmName',
            label: '客户名称'
          },
          {
            prop: 'csmType',
            label: '客户类型',
            render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.customerTypeMap, 'value', row.csmType, 'desc') }</span>
          },
          {
            prop: 'openId',
            label: '微信用户',
            render: (h, { row }) => row.openId && <svg-icon icon-class='wechat-icon' />
          },
          {
            prop: 'csmQuality',
            label: '客户等级',
            render: (h, { row }) => {
              if (this.csmLerel === 1) return <span>{ row.csmQuality ? formatColumnMap(this.csmLevelMap, 'value', row.csmQuality, 'desc') : '' }</span>
              else {
                if (row.qualityStatus === 2) {
                  return <span>{ row.unCheckQuality ? formatColumnMap(this.csmLevelMap, 'value', row.unCheckQuality, 'desc') : '' }</span>
                } else {
                  return <span style='color: red;'>{ row.unCheckQuality ? formatColumnMap(this.csmLevelMap, 'value', row.unCheckQuality, 'desc') : '' }</span>
                }
              }
            }
          },
          {
            prop: 'csmRgPhone',
            width: 110,
            label: '联系电话'
          },
          {
            prop: 'newType',
            label: '开户类型',
            render: (h, { row }) => <span>{ row.newType ? formatColumnMap(this.csmNewTypeMap, 'value', row.newType, 'desc') : '租用瓶' }</span>
          },
          {
            prop: 'newFrom',
            width: 150,
            label: '客户来源',
            render: (h, { row }) => <span>{ row.newFrom && formatColumnMap(this.newFromMap, 'value', row.newFrom, 'desc') }</span>
          },
          {
            prop: 'deposit',
            label: '押金'
          },
          {
            prop: 'csmRgAddress',
            width: 200,
            label: '地址'
          },
          {
            prop: 'nearStationName',
            width: 150,
            label: '所属机构'
          },
          {
            prop: 'cardCount',
            label: '充值卡',
            render: (h, { row }) => row.cardCount ? <el-link style='margin-right: 0;' onClick={() => this.openRefillCard(row)}>{row.cardCount}</el-link> : <span>{row.cardCount}</span>
          },
          {
            prop: 'lastSCheckDt',
            width: 180,
            label: '最后安检时间',
            render: (h, { row }) => row.lastSCheckDt && (new Date(row.lastSCheckDt).getTime() >= new Date(minDate).getTime()) && <span>{ parseTime(row.lastSCheckDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'lastBuyDt',
            width: 180,
            label: '最后订气时间',
            render: (h, { row }) => row.lastBuyDt && (new Date(row.lastBuyDt).getTime() >= new Date(minDate).getTime()) && <span>{ parseTime(row.lastBuyDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'score',
            label: '积分'
          },
          {
            prop: 'totalGasCount',
            label: '使用瓶数'
          },
          {
            prop: 'isPickUp',
            label: '自提客户',
            render: (h, { row }) => <span>{ row.isPickUp === 1 ? '是' : '否' }</span>
          },
          {
            prop: 'settlementType',
            label: '结款方式',
            render: (h, { row }) => <span>{ row.settlementType === 1 ? '现结' : '月结' }</span>
          },
          {
            prop: 'csmStatus',
            label: '状态',
            render: (h, { row }) => <span>{ row.csmStatus && formatColumnMap(this.csmStatusMap, 'value', row.csmStatus, 'desc') }</span>
          },
          {
            prop: 'createTime',
            width: 110,
            label: '开户日期',
            render: (h, { row }) => <span>{ row.createTime && (new Date(row.createTime).getTime() >= new Date(minDate).getTime()) && parseTime(row.createTime, '{y}-{m}-{d}') }</span>
          },
          {
            prop: 'createUser',
            label: '开户人'
          },
          {
            prop: 'salesmanName',
            label: '销售人员'
          },
          {
            prop: 'cancelTime',
            width: 110,
            label: '销户日期',
            render: (h, { row }) => <span>{ row.cancelTime && (new Date(row.cancelTime).getTime() >= new Date(minDate).getTime()) && parseTime(row.cancelTime, '{y}-{m}-{d}') }</span>
          },
          {
            prop: 'cancelUser',
            label: '销户人'
          },
          {
            prop: 'invalidStr',
            label: '销户原因'
          },
          {
            prop: 'curGasCount',
            label: '占用瓶数',
            render: (h, { row }) => row.curGasCount ? <el-link style='margin-right: 0;' onClick={() => this.openOccupy(row)}>{row.curGasCount}</el-link> : <span>{row.curGasCount}</span>
          },
          {
            prop: 'remark',
            width: 200,
            label: '备注'
          },
          {
            prop: 'csmOption3',
            label: '售卖方式'
          },
          {
            prop: 'csmOption5',
            label: '安全合同'
          },
          {
            prop: 'auditor',
            label: '审核人'
          },
          {
            prop: 'sfzh',
            width: 200,
            label: '身份证号'
          },
          {
            prop: 'contractNumber',
            label: '合同号'
          },
          {
            label: '操作',
            className: 'action-col',
            width: this.actionColWidth,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  {row.csmStatus !== -1 && row.csmStatus !== 2 && <el-link size='mini' onClick={() => this.update(row, 'audit')}>
                    审核
                  </el-link>}
                  {row.csmStatus !== -1 && <el-link size='mini' onClick={() => this.update(row, 'edit')}>
                    编辑
                  </el-link>}
                  {row.csmStatus !== -1 && <el-link size='mini' onClick={() => this.insurance(row, $index)}>
                    投保
                  </el-link>}
                  {row.csmStatus !== -1 && <el-link size='mini' onClick={() => this.normalReceiptsAdd(row, $index)}>
                    押金登记
                  </el-link>}
                  {row.csmStatus !== 1 && row.csmStatus !== -1 && <el-link size='mini' type='danger' onClick={() => this.del(row, $index)}>
                    销户
                  </el-link>}
                </div>
              )
            }
          }
        ]
        if (this.userInfo.corpCode !== '22016') {
          const csmOption3 = cols.findIndex(item => item.prop === 'csmOption3')
          cols.splice(csmOption3, 1)
          const csmOption5 = cols.findIndex(item => item.prop === 'csmOption5')
          cols.splice(csmOption5, 1)
        }
        return cols
      }
    },
    mounted() {
      // console.log(this.csmStatusMap, 'this.csmStatusMap')
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        query[this.qtype] = this.txt
        if (this.qtype === 'cardType1') {
          query.cardType = 1
          query.cardNo = this.txt
          delete query.cardType1
        } else if (this.qtype === 'cardType2') {
          query.cardType = 2
          query.cardNo = this.txt
          delete query.cardType2
        }
        if (this.qtype !== 'cardType1' && this.qtype !== 'cardType2') {
          if (query.cardNo) delete query.cardNo
        }
        if (this.date && this.date.length === 2) {
          query[this.dateType] = moment(this.date[0]).format()
          query[`${this.dateType}End`] = moment(this.date[1]).format()
        }
        let csmQuality = this.query.unCheckQuality
        if (this.customerLerel === 1) {
          query.csmQuality = csmQuality
        } else {
          if (!csmQuality) {
            csmQuality = 0
          }
          query.unCheckQuality = csmQuality
        }
        console.log(query)
        const res = await csmManageQueryList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 打开客户详情弹窗
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row)
      },
      // 新增
      async addCsm() {
        await this.$refs.addCsm.open()
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 审核
      async customerAudit(row) {
        const code = {
          csmCode: row.csmCode
        }
        const res = await customerInfo(code)
        const csmId01 = {
          csmId: row.csmId,
          taxType: 1
        }
        const csmId02 = {
          csmId: row.csmId,
          taxType: 2
        }
        const res01 = await customerInvocie(csmId01)
        const res02 = await customerInvocie(csmId02)
        await this.$refs.customerAudit.open(res, res01, res02)
      },
      // 编辑
      async update(row, type) {
        const code = {
          csmCode: row.csmCode
        }
        const res = await customerInfo(code)
        const csmId01 = {
          csmId: row.csmId,
          taxType: 1
        }
        const csmId02 = {
          csmId: row.csmId,
          taxType: 2
        }
        var list = [res.data.provinceCode, res.data.cityCode, res.data.countryCode, res.data.streetCode].filter(l => l * 1 !== 0 && l !== undefined)

        res.data.AddressData = [...list]
        const res01 = await customerInvocie(csmId01)
        const res02 = await customerInvocie(csmId02)
        await this.$refs.editCsm.open(res, res01, res02, type)
        this.$refs.editCsm.$refs.clientInformation.cascaderKey++
      },
      // 投保
      async insurance(row) {
        await this.$refs.insure.open(row)
      },
      // 押金登记
      async normalReceiptsAdd(row) {
        // console.log(row, 'row')
        const res = await customerInfo({ csmCode: row.csmCode })
        console.log(res, 'res')
        await this.$refs.normalReceiptsAdd.open(res.data, 'add')
      },
      // 充值卡
      async openRefillCard(row) {
        await this.$refs.refillCard.open(row)
      },
      // 占用瓶
      async openOccupy(row) {
        await this.$refs.occupy.open(row)
      },
      // 获取选中
      handleCurrentChange(val) {
        this.ids = val
      },
      // 客户位置
      async getMap() {
        if (this.ids === null || this.ids.length === 0) {
          this.$message({
            message: '请选择一名客户',
            type: 'warning'
          })
        } else {
          const code = {
            csmCode: this.ids.csmCode
          }
          const res = await customerLocation(code)
          // console.log(res)
          this.$refs.customerLocation.open(res)
        }
      },
      batchAudit() {},
      batchEdit() {},
      exportFile() {
        const query = {
          ...this._getQuery(this.query)
        }
        query[this.qtype] = this.txt
        if (this.qtype === 'cardType1') {
          query.cardType = 1
          query.cardNo = this.txt
          delete query.cardType1
        } else if (this.qtype === 'cardType2') {
          query.cardType = 2
          query.cardNo = this.txt
          delete query.cardType2
        }
        if (this.qtype !== 'cardType1' && this.qtype !== 'cardType2') {
          if (query.cardNo) delete query.cardNo
        }
        if (this.date && this.date.length === 2) {
          query[this.dateType] = moment(this.date[0]).format()
          query[`${this.dateType}End`] = moment(this.date[1]).format()
        }
        let csmQuality = this.query.unCheckQuality
        if (this.customerLerel === 1) {
          query.csmQuality = csmQuality
        } else {
          if (!csmQuality) {
            csmQuality = 0
          }
          query.unCheckQuality = csmQuality
        }
        var list = JSON.parse(JSON.stringify(this.column))
        list.pop()
        list.shift()
        const value = {}
        list.forEach(l => {
          value[l.prop] = l.label
          return value
        })
        this.$refs.export.open(query, value)
      },
      del(row, index) {
        const code = {
          csmId: row.csmId
        }
        this.$refs.xiaohu.open(code)
      },
      async xiaoHuFn(params) {
        const res = await customerCancle(params)
        if (res.success) {
          this.$message.success('销户成功')
          this.$refs.lbTable.fetch({ currentPage: 1 })
        }
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
